package comp;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.dom4j.DocumentException;

import util.PatternPlainTextParser;
import util.PatternXMLParser;

public class PatternLoader {
	private String repo;
	private FileType type;
	
	
	public PatternLoader(String repo, FileType type){
		this.repo = repo;
		this.type = type;
	}
	
	public Map<String, Set<Enum>> load(String separator) throws ClassNotFoundException, DocumentException, FileNotFoundException{
		if(type == FileType.XML){
			return loadXML();
		}else if(type == FileType.PlainText){
			return loadPlainText(separator);
		}
		throw new RuntimeException("Unsupported file type");
	}
	
	public Map<String, Set<Enum>> loadPlainText(String separator) throws ClassNotFoundException, DocumentException, FileNotFoundException{
		List<String> fileList = getFilesFromDir(repo,".dp");
		
		PatternPlainTextParser ptp = new PatternPlainTextParser(separator);
		Map<String,Set<Enum>> patternMap = ptp.parse(fileList);
		
		return patternMap;	
	}
	private  Map<String, Set<Enum>> loadXML() throws ClassNotFoundException, DocumentException{
		//get list of files in the known pattern repository
		List<String> fileList = getFilesFromDir(repo,".xml");
				
		PatternXMLParser xp = new PatternXMLParser();
		Map<String,Set<Enum>> patternMap = xp.parse(fileList);
		return patternMap;	
		
	}
	private  List<String> getFilesFromDir(String dirPath,String suffix){
		List<String> files = new ArrayList<String>();
		File dir = new File(dirPath);
		for(String fName : dir.list()){
			if(fName.toLowerCase().endsWith(suffix)){
				files.add(dir.getPath()+File.separator+fName);
			}
		}
		return files;
	}
	
	public enum FileType{
		XML, PlainText;
	}

}
